/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * bocciawii
 * Copyright (C) Grupo de trabajo ULE 2010 <ulewii@googlegroups.com>
 * 
 * teclado is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * teclado is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "screen-layout.h"

ScreenLayout::ScreenLayout(int filas, int cols)
{
	_numFilas = filas;
	_numCols = cols;

	for (int i = 0; i < 10; i++)
		for (int j = 0; j < 10; j++)
			conts[i][j] = NULL;
}

ScreenLayout::~ScreenLayout()
{
	for (int i = 0; i < _numFilas; i++)
		for (int j = 0; j < _numCols; j++)
			if (conts[i][j] != NULL)
				conts[i][j]->~LinkedContainer();
}

void ScreenLayout::Append(LinkedContainer* cont, int x, int y)
{
	conts[x][y] = cont;
}

Elemento* ScreenLayout::GetElemByID(std::string id)
{
	int found = 0;
	
	for (int i = 0; i < _numFilas; i++)
	{
		for (int j = 0; j < _numCols; j++)
			if (conts[i][j] != NULL)
			{
				if (conts[i][j]->GetElemByID(id) != NULL)
					return conts[i][j]->GetElemByID(id);
			}
	}
}

void ScreenLayout::Pack(int pantalla_x, int pantalla_y)
{
	_pantX = pantalla_x;
	_pantY = pantalla_y;

	int ancho_area = pantalla_x / _numCols;
	int alto_area = pantalla_y / _numFilas;

	for (int i = 0; i < _numFilas; i++)
		for (int j = 0; j < _numCols; j++)
			if (conts[i][j]!= NULL)
	{
				conts[i][j]->Pack(ancho_area * j + ancho_area / 2,
								  alto_area * i + alto_area / 2);
	}
	
}

void ScreenLayout::Dibujar()
{
	if (!_visible)
		return;
	
	SetOrtho();
	
	for (int i = 0; i < _numFilas; i ++)
		for (int j = 0; j < _numCols; j++)
			if (conts[i][j] != NULL)
			    conts[i][j]->Dibujar();
	
	UnsetOrtho ();

}

void ScreenLayout::SetOrtho()
{
	glDisable ( GL_DEPTH_TEST );
	glDisable ( GL_LIGHTING );
	
	glMatrixMode (GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(0, _pantX, _pantY, 0);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
}

void ScreenLayout::UnsetOrtho()
{
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	
	glEnable( GL_DEPTH_TEST );
	glEnable( GL_LIGHTING );
	
    gluPerspective(45.0f, (GLfloat)_pantX/(GLfloat)_pantY,1.0,100.0);
}